package com.example.systemserver.service;

import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.jwt.JWTUtil;
import com.example.systemserver.bean.AccountBean;
import com.example.systemserver.config.MyException;
import com.example.systemserver.mapper.AccountMapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;

@Slf4j
@Service
public class AccountService {

    @Resource
    private AccountMapper accountMapper;


    public String login(AccountBean bean) {
        log.debug("用户登录,检查参数");
        if (bean == null) {
            throw new MyException("参数不能为空");
        }
        if (bean.getUsername() == null || bean.getUsername().trim().isEmpty()) {
            throw new MyException("用户名不能为空");
        }
        if (bean.getPassword() == null || bean.getPassword().trim().isEmpty()) {
            throw new MyException("密码不能为空");
        }

        log.debug("用户登录,根据用户名查询账户信息");
        AccountBean accountBean = accountMapper.info(bean);
        if (accountBean == null) {
            throw new MyException("用户名密码不匹配");
        }
        String md5 = DigestUtil.md5Hex(bean.getPassword());
        if (!md5.equals(accountBean.getPassword())) {
            throw new MyException("用户名密码不匹配");
        }

        log.debug("用户登录,登录成功,返回token值");
        HashMap<String, Object> map = new HashMap<>();
        map.put("timeout",System.currentTimeMillis()+24*60*60*1000);
        map.put("id",accountBean.getId());
        String token = JWTUtil.createToken(map,"1234567".getBytes(StandardCharsets.UTF_8));
        return token;
    }
}
